package com.local.consumer.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class RabbitMQConfig {
    @Value("${rabbitmqs.order-exchange}")
    private String orderExchange;

    @Value("${rabbitmqs.order-queue}")
    private String orderQueue;

    @Value("${rabbitmqs.order-queue-routing-key}")
    private String orderQueueRoutingKey;

    @Value("${rabbitmqs.order-dead-letter-exchange}")
    private String orderDeadLetterExchange;

    @Value("${rabbitmqs.order-dead-letter-queue}")
    private String orderDeadLetterQueue;

    @Value("${rabbitmqs.order-dead-letter-routing-key}")
    private String orderDeadLetterRoutingKey;

    @Bean
    public TopicExchange orderDeadLetterExchange() {
        return new TopicExchange(this.orderDeadLetterExchange);
    }

    @Bean
    public Queue orderDeadLetterQueue() {
        return new Queue(this.orderDeadLetterQueue);
    }

    @Bean
    public Binding bindOrderDeadLetterQueueExchange(Queue orderDeadLetterQueue, TopicExchange orderDeadLetterExchange) {
        return BindingBuilder
                .bind(orderDeadLetterQueue)
                .to(orderDeadLetterExchange)
                .with(this.orderDeadLetterRoutingKey);
    }

    @Bean
    public TopicExchange orderExchange() {
        return new TopicExchange(this.orderExchange);
    }

    @Bean
    public Queue orderQueue() {
        Map<String, Object> args = new HashMap<>(4);
//       x-dead-letter-exchange    这里声明当前队列绑定的死信交换机
        args.put("x-dead-letter-exchange", this.orderDeadLetterExchange);
//       x-dead-letter-routing-key  这里声明当前队列的死信路由key
        args.put("x-dead-letter-routing-key", this.orderDeadLetterRoutingKey);

        return new Queue(this.orderQueue, true, false, false, args);
    }

    @Bean
    public Binding bindOrderQueueExchange(Queue orderQueue, TopicExchange orderExchange) {
        return BindingBuilder
                .bind(orderQueue)
                .to(orderExchange)
                .with(this.orderQueueRoutingKey);
    }

    /**
     * 对rabbitmq的Object类型的消息进行json处理（Object的bean要实现Serializable接口）
     * @return
     */
    @Bean
    public MessageConverter jsonMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }
}
